//
// Created by 29108 on 2025/6/29.
//
#include "common/logger/logger.h"
#include "common/config/config_manager.h"
#include <algorithm>

namespace common {
    namespace logger {
        // ConsoleSink 实现
        void ConsoleSink::write(const LogEntry& entry) {
            // 设置不同日志级别的颜色
            const char* color = "";
            switch (entry.level) {
                case LogLevel::TRACE:   color = "\033[37m"; break; // 白色
                case LogLevel::DEBUG:   color = "\033[36m"; break; // 青色
                case LogLevel::INFO:    color = "\033[32m"; break; // 绿色
                case LogLevel::WARNING: color = "\033[33m"; break; // 黄色
                case LogLevel::ERROR:   color = "\033[31m"; break; // 红色
                case LogLevel::FATAL:   color = "\033[35m"; break; // 紫色
            }

            std::cout << color
              << "[" << Logger::formatTimestamp(entry.timestamp) << "] "
              << "[" << Logger::levelToString(entry.level) << "] "
              << "[" << entry.threadId << "] "
              // 添加__FILE__和__LINE__
              << "[" << entry.file << ":" << entry.line << "] "  // 需在LogEntry中新增字段
              << entry.message
              << "\033[0m" << std::endl;
        }

        // FileSink 实现
        FileSink::FileSink(const std::string& filename) {
            file_.open(filename, std::ios::out | std::ios::app);
            if (!file_.is_open()) {
                throw std::runtime_error("无法打开日志文件：" + filename);
            }
        }

        FileSink::~FileSink() {
            if (file_.is_open()) {
                flush();
                file_.close();
            }
        }

        void FileSink::write(const LogEntry& entry) {
            std::lock_guard<std::mutex> lock(fileMutex_);

            file_ << "[" << Logger::formatTimestamp(entry.timestamp) << "] "
                  << "[" << Logger::levelToString(entry.level) << "] "
                  << "[" << entry.threadId << "] "
                  << "[" << entry.file << ":" << entry.line << "] "
                  << entry.message << std::endl;

            // 立即刷新到磁盘，确保数据写入
            file_.flush();
        }

        void FileSink::flush() {
            std::lock_guard<std::mutex> lock(fileMutex_);
            file_.flush();
        }

        // Logger 实现
        Logger& Logger::getInstance() {
            static Logger instance;
            return instance;
        }

        Logger::Logger() :
            config_(),
            level_(LogLevel::INFO),
            async_enabled_(false),
            config_initialized_(false),
            thread_pool_(nullptr) {

            // 先添加基本的控制台输出，确保在配置加载前也能工作
            addSink(std::make_shared<ConsoleSink>());

            // 尝试从配置初始化，如果失败则使用默认配置
            try {
                initializeFromConfig();
            } catch (const std::exception& e) {
                // 配置加载失败，使用默认配置
                std::cerr << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Config initialization failed, using defaults: " << e.what() << std::endl;
                // 添加默认文件输出
                addSink(std::make_shared<FileSink>("./logs/game_service.log"));
            }
        }

        Logger::~Logger() {
            stopAsync();
            flushAll();

            // 关闭ThreadPool
            shutdownThreadPool();
        }

        void Logger::addSink(std::shared_ptr<LogSink> sink) {
            std::lock_guard<std::mutex> lock(sinkMutex_);
            sinks_.push_back(sink);
        }

        void Logger::removeSink(std::shared_ptr<LogSink> sink) {
            std::lock_guard<std::mutex> lock(sinkMutex_);
            auto it = std::find(sinks_.begin(), sinks_.end(), sink);
            if (it != sinks_.end()) {
                sinks_.erase(it);
            }
        }

        void Logger::clearSinks() {
            std::lock_guard<std::mutex> lock(sinkMutex_);
            sinks_.clear();
        }

        void Logger::initializeFromConfig() {
            // 防止重复初始化
            if (config_initialized_.load()) {
                std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Already initialized from config, skipping" << std::endl;
                return;
            }

            try {
                auto config = Config::fromConfigManager();
                config.validate();

                // 设置全局日志级别
                setLevel(config.level);

                // 清除现有的sinks
                {
                    std::lock_guard<std::mutex> lock(sinkMutex_);
                    sinks_.clear();
                }

                // 根据配置添加sinks
                if (config.console_enabled) {
                    auto console_sink = std::make_shared<ConsoleSink>();
                    addSink(console_sink);
                    // 避免在初始化过程中使用LOG宏，防止递归
                    std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Console logging enabled" << std::endl;
                }

                if (config.file_enabled) {
                    // 确保日志目录存在
                    std::filesystem::path log_path(config.file_path);
                    if (log_path.has_parent_path()) {
                        std::filesystem::create_directories(log_path.parent_path());
                    }

                    auto file_sink = std::make_shared<FileSink>(config.file_path);
                    addSink(file_sink);
                    std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] File logging enabled: " << config.file_path << std::endl;
                }

                // 保存配置
                config_ = config;

                // 初始化ThreadPool（如果启用）
                if (config.use_thread_pool) {
                    initializeThreadPool();
                    std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] ThreadPool enabled with " << config.thread_pool_core_size
                              << " core threads, " << config.thread_pool_max_size << " max threads" << std::endl;
                }

                // 启动异步处理（如果启用）
                if (config.async_enabled) {
                    startAsync();
                    std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Async logging enabled with queue size: " << config.async_queue_size << std::endl;
                }

                config_initialized_ = true;
                std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Logger initialized from config successfully" << std::endl;

            } catch (const std::exception& e) {
                std::cerr << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Failed to initialize from config: " << e.what() << std::endl;
                // 保持默认的控制台输出
            }
        }

        void Logger::enableConfigHotReload() {
            auto& config_manager = common::config::ConfigManager::getInstance();

            // 监听日志级别变化
            config_manager.addChangeListener("logging.level",
                [this](const auto& /* key */, const auto& old_val, const auto& new_val) {
                    // 避免递归调用，使用标准输出
                    std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Log level changed from " << old_val << " to " << new_val << std::endl;

                    // 动态调整日志级别
                    LogLevel new_level = LogLevel::INFO;
                    if (new_val == "LOG_DEBUG") new_level = LogLevel::DEBUG;
                    else if (new_val == "LOG_INFO") new_level = LogLevel::INFO;
                    else if (new_val == "LOG_WARNING" || new_val == "LOG_WARN") new_level = LogLevel::WARNING;
                    else if (new_val == "LOG_ERROR") new_level = LogLevel::ERROR;
                    else if (new_val == "LOG_FATAL") new_level = LogLevel::FATAL;

                    this->setLevel(new_level);
                });

            // 监听文件日志路径变化
            config_manager.addChangeListener("logging.file.path",
                [this](const auto& /* key */, const auto& old_val, const auto& new_val) {
                    // 避免递归调用，使用标准输出
                    std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Log file path changed from " << old_val << " to " << new_val << std::endl;
                    // 重新初始化文件日志
                    this->reinitializeFileSink(new_val);
                });
        }

        void Logger::log(LogLevel level, const std::string& message, const char* file, int line) {
            if (level < level_) {
                return;
            }

            LogEntry entry(message, level, file, line);

            // 根据配置选择处理方式
            if (async_enabled_) {
                // 异步模式：添加到队列，由异步线程处理
                std::unique_lock<std::mutex> lock(async_mutex_);

                // 检查队列大小，防止内存耗尽
                if (async_queue_.size() >= 10000) {  // 队列大小限制
                    // 队列满时，丢弃最旧的消息
                    async_queue_.pop();
                    // 可以记录丢弃统计，但避免递归日志
                }

                async_queue_.push(entry);
                lock.unlock();
                async_condition_.notify_one();
            } else if (config_.use_thread_pool && thread_pool_) {
                // ThreadPool模式：直接使用ThreadPool处理
                processLogEntryWithThreadPool(entry);
            } else {
                // 同步模式，直接写入
                if (config_.parallel_sink_processing && sinks_.size() > 1) {
                    // 并行处理多个Sink
                    processLogEntryParallel(entry);
                } else {
                    // 串行处理
                    std::lock_guard<std::mutex> lock(sinkMutex_);
                    for (auto& sink : sinks_) {
                        sink->write(entry);
                    }
                }
            }

            // FATAL级别日志记录完后立即刷新
            if (level == LogLevel::FATAL) {
                flushAll();
                std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] LogLevel::FATAL reached" << std::endl;
                // 不要调用std::exit()，让程序自然退出或由调用者决定
                // 可以抛出异常让调用者处理
                throw std::runtime_error("FATAL log level reached");
            }
        }

        void Logger::startAsync() {
            if (async_enabled_) {
                return; // 已经启用
            }

            async_enabled_ = true;
            async_stop_flag_ = false;

            // 创建异步处理线程
            async_thread_ = std::thread([this]() {
                asyncWorker();
            });

            // 避免在异步启动时使用Logger，防止死锁
            std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Async logging worker thread started" << std::endl;
        }

        void Logger::stopAsync() {
            if (!async_enabled_) {
                return; // 已经禁用
            }

            async_stop_flag_ = true;
            async_condition_.notify_all();

            if (async_thread_.joinable()) {
                async_thread_.join();
            }

            async_enabled_ = false;
            // 避免在停止异步线程时使用Logger，防止死锁
            std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Async logging worker thread stopped" << std::endl;
        }

        void Logger::flushAll() {
            // 复制Sink列表，避免长时间持锁
            std::vector<std::shared_ptr<LogSink>> sinks_copy;
            {
                std::lock_guard<std::mutex> lock(sinkMutex_);
                sinks_copy = sinks_;
            }

            // 在锁外执行flush操作
            for (auto& sink : sinks_copy) {
                try {
                    sink->flush();
                } catch (const std::exception& e) {
                    std::cerr << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Error flushing sink: " << e.what() << std::endl;
                }
            }
        }

        void Logger::reinitializeFileSink(const std::string &new_path) {
            std::lock_guard<std::mutex> lock(sinkMutex_);

            try {
                // 确保新路径的目录存在
                std::filesystem::path log_path(new_path);
                if (log_path.has_parent_path()) {
                    std::filesystem::create_directories(log_path.parent_path());
                }

                // 创建新的文件sink（FileSink构造函数会抛出异常如果文件无法打开）
                auto new_file_sink = std::make_shared<FileSink>(new_path);

                // 移除旧的文件sink
                auto old_sink_count = sinks_.size();
                sinks_.erase(
                    std::remove_if(sinks_.begin(), sinks_.end(),
                        [](const std::shared_ptr<LogSink>& sink) {
                            return std::dynamic_pointer_cast<FileSink>(sink) != nullptr;
                        }),
                    sinks_.end());

                // 添加新的文件sink
                sinks_.push_back(new_file_sink);

                // 避免在初始化过程中使用Logger，防止递归调用
                std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] File sink reinitialized: " << new_path <<
                            " (removed " << (old_sink_count - sinks_.size() + 1) << " old sinks)" << std::endl;

            } catch (const std::exception& e) {
                // 避免在异常处理中使用Logger，防止递归调用
                std::cerr << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Failed to reinitialize file sink: " << e.what() << std::endl;
                throw;
            }
        }

        void Logger::adjustLogLevel(LogLevel new_level) {
            std::lock_guard<std::mutex> lock(sinkMutex_);

            LogLevel old_level = level_;  // 统一使用level_变量
            level_ = new_level;

            // 避免递归调用，使用标准输出
            std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Log level changed from " << levelToString(old_level) <<
                        " to " << levelToString(new_level) << std::endl;
        }

        void Logger::adjustConsoleSettings(bool enabled, bool /* colored */) {
            std::lock_guard<std::mutex> lock(sinkMutex_);

            if (enabled) {
                // 检查是否已有控制台sink
                bool has_console_sink = std::any_of(sinks_.begin(), sinks_.end(),
                    [](const std::shared_ptr<LogSink>& sink) {
                        return std::dynamic_pointer_cast<ConsoleSink>(sink) != nullptr;
                    });

                if (!has_console_sink) {
                    auto console_sink = std::make_shared<ConsoleSink>();
                    sinks_.push_back(console_sink);
                    std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Console logging enabled " << std::endl;
                }
                // 注意：当前ConsoleSink实现不支持动态颜色设置，需要重新创建sink
            } else {
                // 移除控制台sink
                auto old_size = sinks_.size();
                sinks_.erase(
                    std::remove_if(sinks_.begin(), sinks_.end(),
                        [](const std::shared_ptr<LogSink>& sink) {
                            return std::dynamic_pointer_cast<ConsoleSink>(sink) != nullptr;
                        }),
                    sinks_.end());

                if (sinks_.size() < old_size) {
                    std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Console logging enabled " << std::endl;
                }
            }
        }

        void Logger::adjustAsyncSettings(bool enabled, size_t queue_size) {
            std::lock_guard<std::mutex> lock(sinkMutex_);

            if (enabled && !async_enabled_) {
                // 启用异步日志
                async_queue_size_ = queue_size;
                startAsync();
                // 避免在启动异步时使用Logger，防止死锁
                std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Async logging enabled with queue size: " << queue_size << std::endl;
            } else if (!enabled && async_enabled_) {
                // 禁用异步日志
                stopAsync();
                // 避免在停止异步时使用Logger，防止死锁
                std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Async logging disabled" << std::endl;
            } else if (enabled && async_enabled_ && queue_size != async_queue_size_) {
                // 调整队列大小（需要重启异步处理）
                stopAsync();
                async_queue_size_ = queue_size;
                startAsync();
                // 避免在调整异步设置时使用Logger，防止死锁
                std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Async logging queue size adjusted to: " << queue_size << std::endl;
            }
        }

        void Logger::asyncWorker() {
            while (!async_stop_flag_.load()) {
                std::vector<LogEntry> messages_to_process;

                {
                    std::unique_lock<std::mutex> lock(async_mutex_);
                    async_condition_.wait_for(lock, std::chrono::milliseconds(100), [this] {
                        return !async_queue_.empty() || async_stop_flag_.load();
                    });

                    // 批量处理消息
                    while (!async_queue_.empty() && messages_to_process.size() < 100) {
                        messages_to_process.push_back(std::move(async_queue_.front()));
                        async_queue_.pop();
                    }
                }

                // 在锁外处理消息
                for (const auto& message : messages_to_process) {
                    processLogMessage(message);
                }
            }

            // 处理剩余的消息
            std::vector<LogEntry> remaining_messages;
            {
                std::lock_guard<std::mutex> lock(async_mutex_);
                while (!async_queue_.empty()) {
                    remaining_messages.push_back(std::move(async_queue_.front()));
                    async_queue_.pop();
                }
            }

            // 在锁外处理剩余消息
            for (const auto& message : remaining_messages) {
                processLogMessage(message);
            }
        }

        void Logger::processLogMessage(const LogEntry &message) {
            // 复制Sink列表，避免长时间持锁导致死锁
            std::vector<std::shared_ptr<LogSink>> sinks_copy;
            {
                std::lock_guard<std::mutex> lock(sinkMutex_);
                sinks_copy = sinks_;
            }

            // 在锁外处理消息，避免死锁
            for (auto& sink : sinks_copy) {
                try {
                    sink->write(message);
                } catch (const std::exception& e) {
                    // 避免在日志处理中产生无限递归
                    std::cerr << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Log sink error: " << e.what() << std::endl;
                }
            }
        }

        std::string Logger::levelToString(LogLevel level) {
            switch (level) {
                case LogLevel::TRACE:   return "TRACE";
                case LogLevel::DEBUG:   return "DEBUG";
                case LogLevel::INFO:    return "INFO ";
                case LogLevel::WARNING: return "WARN ";
                case LogLevel::ERROR:   return "ERROR";
                case LogLevel::FATAL:   return "FATAL";
                default:                return "UNKN ";
            }
        }

        LogLevel Logger::stringToLogLevel(const std::string& level_str) {
            if (level_str == "LOG_TRACE" || level_str == "TRACE") {
                return LogLevel::TRACE;
            } else if (level_str == "LOG_DEBUG" || level_str == "DEBUG") {
                return LogLevel::DEBUG;
            } else if (level_str == "LOG_INFO" || level_str == "INFO") {
                return LogLevel::INFO;
            } else if (level_str == "LOG_WARNING" || level_str == "WARNING" || level_str == "WARN") {
                return LogLevel::WARNING;
            } else if (level_str == "LOG_ERROR" || level_str == "ERROR") {
                return LogLevel::ERROR;
            } else if (level_str == "LOG_FATAL" || level_str == "FATAL") {
                return LogLevel::FATAL;
            } else {
                // 默认返回INFO级别，并输出警告
                std::cerr << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Invalid log level: " << level_str << ", using INFO as default" << std::endl;
                return LogLevel::INFO;
            }
        }

        std::string Logger::formatTimestamp(const std::chrono::system_clock::time_point& time) {
            auto tt = std::chrono::system_clock::to_time_t(time);
            auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
                          time.time_since_epoch()) % 1000;

            std::tm local_tm;
            localtime_r(&tt, &local_tm);

            std::ostringstream oss;
            oss << std::put_time(&local_tm, "%Y-%m-%d %H:%M:%S")
                << '.' << std::setfill('0') << std::setw(3) << ms.count();

            return oss.str();
        }

        void Logger::initializeThreadPool() {
            if (!config_.use_thread_pool) {
                return;
            }

            try {
                // 创建ThreadPool配置
                common::thread_pool::ThreadPool::Config pool_config;
                pool_config.core_pool_size = config_.thread_pool_core_size;
                pool_config.maximum_pool_size = config_.thread_pool_max_size;
                pool_config.queue_capacity = config_.thread_pool_queue_capacity;
                pool_config.enable_monitoring = config_.enable_thread_pool_monitoring;
                pool_config.rejection_policy = "caller_runs";  // 主线程执行被拒绝的任务

                // 创建ThreadPool实例
                thread_pool_ = std::make_unique<common::thread_pool::ThreadPool>(pool_config);

                std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] ThreadPool initialized: core=" <<
                            config_.thread_pool_core_size <<
                            ", max=" << config_.thread_pool_max_size <<
                            ", queue=" << config_.thread_pool_queue_capacity << std::endl;

            } catch (const std::exception& e) {
                std::cerr << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Failed to initialize ThreadPool: " << e.what() << std::endl;
                thread_pool_.reset();
                config_.use_thread_pool = false;  // 降级到传统模式
            }
        }

        void Logger::shutdownThreadPool() {
            if (thread_pool_) {
                try {
                    std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Shutting down ThreadPool..." << std::endl;
                    thread_pool_->shutdown();
                    thread_pool_.reset();
                    std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] ThreadPool shutdown completed" << std::endl;
                } catch (const std::exception& e) {
                    std::cerr << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Error during ThreadPool shutdown: " << e.what() << std::endl;
                    thread_pool_.reset();
                }
            }
        }

        void Logger::processLogEntryWithThreadPool(const LogEntry& entry) {
            if (!thread_pool_) {
                // 降级到同步处理
                std::lock_guard<std::mutex> lock(sinkMutex_);
                for (auto& sink : sinks_) {
                    sink->write(entry);
                }
                return;
            }

            // 提交任务到ThreadPool
            thread_pool_tasks_submitted_.fetch_add(1);

            if (config_.parallel_sink_processing && sinks_.size() > 1) {
                // 并行处理每个Sink - 先复制sinks避免死锁
                std::vector<std::shared_ptr<LogSink>> sinks_copy;
                {
                    std::lock_guard<std::mutex> lock(sinkMutex_);
                    sinks_copy = sinks_;  // 复制sinks列表
                }

                for (auto& sink : sinks_copy) {
                    try {
                        thread_pool_->submit([this, entry, sink]() {
                            try {
                                sink->write(entry);
                                thread_pool_tasks_completed_.fetch_add(1);
                            } catch (const std::exception& e) {
                                std::cerr << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Error writing to sink: " << e.what() << std::endl;
                            }
                        });
                    } catch (const std::exception& e) {
                        // ThreadPool可能已停止，回退到同步处理
                        std::cerr << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] ThreadPool submit failed, falling back to sync: " << e.what() << std::endl;
                        try {
                            sink->write(entry);
                        } catch (const std::exception& sink_e) {
                            std::cerr << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Sync write failed: " << sink_e.what() << std::endl;
                        }
                    }
                }
            } else {
                // 串行处理所有Sink - 先复制sinks避免死锁
                std::vector<std::shared_ptr<LogSink>> sinks_copy;
                {
                    std::lock_guard<std::mutex> lock(sinkMutex_);
                    sinks_copy = sinks_;  // 复制sinks列表
                }

                try {
                    thread_pool_->submit([this, entry, sinks_copy]() {
                        try {
                            for (auto& sink : sinks_copy) {
                                sink->write(entry);
                            }
                            thread_pool_tasks_completed_.fetch_add(1);
                        } catch (const std::exception& e) {
                            std::cerr << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Error writing to sinks: " << e.what() << std::endl;
                        }
                    });
                } catch (const std::exception& e) {
                    // ThreadPool可能已停止，回退到同步处理
                    std::cerr << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] ThreadPool submit failed, falling back to sync: " << e.what() << std::endl;
                    try {
                        for (auto& sink : sinks_copy) {
                            sink->write(entry);
                        }
                    } catch (const std::exception& sink_e) {
                        std::cerr << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Sync write failed: " << sink_e.what() << std::endl;
                    }
                }
            }
        }

        void Logger::processBatchLogEntries(const std::vector<LogEntry>& entries) {
            if (!thread_pool_) {
                // 降级到同步处理
                std::lock_guard<std::mutex> lock(sinkMutex_);
                for (const auto& entry : entries) {
                    for (auto& sink : sinks_) {
                        sink->write(entry);
                    }
                }
                return;
            }

            // 批量提交到ThreadPool
            thread_pool_->submit([this, entries]() {
                try {
                    std::lock_guard<std::mutex> lock(sinkMutex_);
                    for (const auto& entry : entries) {
                        for (auto& sink : sinks_) {
                            sink->write(entry);
                        }
                    }
                    thread_pool_tasks_completed_.fetch_add(1);
                } catch (const std::exception& e) {
                    std::cerr << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Error in batch processing: " << e.what() << std::endl;
                }
            });
        }

        void Logger::processLogEntryParallel(const LogEntry& entry) {
            if (!thread_pool_) {
                // 降级到同步处理
                std::lock_guard<std::mutex> lock(sinkMutex_);
                for (auto& sink : sinks_) {
                    sink->write(entry);
                }
                return;
            }

            // 为每个Sink创建并行任务 - 先复制sinks避免长时间持锁
            std::vector<std::shared_ptr<LogSink>> sinks_copy;
            {
                std::lock_guard<std::mutex> lock(sinkMutex_);
                sinks_copy = sinks_;  // 复制sinks列表
            }

            for (auto& sink : sinks_copy) {
                thread_pool_->submit([entry, sink]() {
                    try {
                        sink->write(entry);
                    } catch (const std::exception& e) {
                        std::cerr << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Error writing to parallel sink: " << e.what() << std::endl;
                    }
                });
            }
        }

        std::string Logger::getThreadPoolStatus() const {
            if (!thread_pool_) {
                return "ThreadPool not available";
            }

            return "ThreadPool Status: " +
                   std::to_string(thread_pool_->getActiveThreadCount()) + "/" +
                   std::to_string(thread_pool_->getTotalThreadCount()) + " threads active, " +
                   std::to_string(thread_pool_->getQueueSize()) + " tasks queued, " +
                   std::to_string(thread_pool_tasks_submitted_.load()) + " submitted, " +
                   std::to_string(thread_pool_tasks_completed_.load()) + " completed";
        }

        size_t Logger::getActiveThreadCount() const {
            return thread_pool_ ? thread_pool_->getActiveThreadCount() : 0;
        }

        size_t Logger::getThreadPoolQueueSize() const {
            return thread_pool_ ? thread_pool_->getQueueSize() : 0;
        }

        bool Logger::adjustThreadPoolSize(int core_size, int max_size) {
            if (!thread_pool_) {
                std::cerr << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Cannot adjust ThreadPool size: ThreadPool not available" << std::endl;
                return false;
            }

            try {
                thread_pool_->adjustCorePoolSize(core_size);
                thread_pool_->adjustMaximumPoolSize(max_size);

                // 更新配置
                config_.thread_pool_core_size = core_size;
                config_.thread_pool_max_size = max_size;

                std::cout << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] ThreadPool size adjusted: core=" << core_size <<
                            ", max=" << max_size << std::endl;
                return true;

            } catch (const std::exception& e) {
                std::cerr << "[Logger] [" << __FILE__ << ":" << __LINE__ << "] Failed to adjust ThreadPool size: " << e.what() << std::endl;
                return false;
            }
        }

        void Logger::forceFlush() {
            // 等待异步队列处理完成
            if (async_enabled_) {
                // 等待异步队列为空
                while (true) {
                    {
                        std::lock_guard<std::mutex> lock(async_mutex_);
                        if (async_queue_.empty()) {
                            break;
                        }
                    }
                    std::this_thread::sleep_for(std::chrono::milliseconds(10));
                }
            }

            // 等待ThreadPool中的所有任务完成
            if (thread_pool_) {
                while (thread_pool_->getQueueSize() > 0 || thread_pool_->getActiveThreadCount() > 0) {
                    std::this_thread::sleep_for(std::chrono::milliseconds(10));
                }
            }

            // 刷新所有Sink
            flushAll();
        }
    }
}